package com.qb.devmgt;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.widget.Button;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import utils.DownloadUtil;
import utils.MyUtil;
import utils.SystemPropertiesReflection;

public class MainActivity extends AppCompatActivity {

    TextView tvMsg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvMsg = findViewById(R.id.tv_msg);

        System.out.println("********rrr*******");
        MyUtil.showLog("ssssssssssss", SystemPropertiesReflection.demo);

//        downloadAnimation(this);

        Button btnPush = findViewById(R.id.btn_push);
        btnPush.setOnClickListener(view -> {
            downloadAnimation(this);
        });

        Button btnClear = findViewById(R.id.btn_clear);
        btnClear.setOnClickListener(view -> {
            setAnimationByRoot(0);
        });
    }

    // 获取不同主板的开机画面文件路径
    public String getBootAnimationPath() {
        String bootDir = "/system/media/";
        String board = SystemPropertiesReflection.USER;
        if (board.equals("XHZY")) bootDir = "/data/local/";
        if (board.equals("zim")) bootDir = "/odm/media/";
        return bootDir;
    }

    // 设置开机画面
    public void setAnimationByRoot(int fun) {
        System.out.println("********setAnimationByRoot-111*******");
        String r = "";
        System.out.println(r);
        r = runCommandSu("root");
        System.out.println("********setAnimationByRoot-222*******");
        System.out.println(r);
        if (r.equals("")) {
            r = runCommandSu("remount");
            System.out.println("********setAnimationByRoot-333*******");
            System.out.println(r);
            if (r.equals("remount succeeded")) {
                if (fun == 1) {
                    if (isExists(getBootAnimationPath())) {
                        copyBootAnimation();
                    } else {
                        r = runCommandSu("mkdir "+getBootAnimationPath());
                        System.out.println("********setAnimationByRoot-444*******");
                        System.out.println(r);
                        if (r.equals("")) {
                            copyBootAnimation();
                        } else setText(r);
                    }
                } else if (fun == 0) {
                    clearAnimation();
                }
            } else setText(r);
        } else setText(r);
    }

    // 下载开机画面
    public void downloadAnimation(Context ctx) {
        String url = "http://192.168.6.86:8086/xiazaiba/bootanimation/bootanimation.zip";
        String name = "ba.zip";
        setText("开始从"+url+"下载开机画面文件");
        downLoad(ctx, url, name, "bootanimation", false);
    }

    //下载文件
    public void downLoad(Context ctx,String url,String name,String flag,Boolean isConfirm) {
        String destFileDir = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "Download/";
        destFileDir = "/sdcard/Download/";
        final int[] currentProgress = {0};
        if(MyUtil.isFolderExists(destFileDir)) {
            MyUtil.showLog("downLoad","开始下载:"+name);
            DownloadUtil dlu = new DownloadUtil(url);
            dlu.download(destFileDir, name, new DownloadUtil.OnDownloadListener() {
                @Override
                public void onDownloadSuccess(File file) {
                    MyUtil.showLog("downLoad","下载完成");
                    setText("下载完成，开机画面设置中……");
                    if (flag.equals("bootanimation")) {
                        Looper.prepare();
                        new Handler().postDelayed(()-> {
//                            copyBootAnimation();
                            setAnimationByRoot(1);
                        },3000);
                        Looper.loop();
                    }
                }

                @Override
                public void onDownloading(int progress) {
                    //下载进行中展示进度
                    String title = "正在下载"+name;
                    if (progress > currentProgress[0]) {
                        MyUtil.showLog("downLoad","下载进度:"+progress);
                        MyUtil.showLog("downLoad progress="+progress,currentProgress[0]);
                        currentProgress[0] = progress;
                    }
                }

                @Override
                public void onDownloadFailed(Exception e) {
                    //下载异常进行相关提示操作
                    MyUtil.showLog("downLoad",name+"下载失败"+e);
                    setText(name+"下载失败"+e);
                }
            });
        } else {
            MyUtil.showLog("downLoad",name+"下载失败"+"目录不存在");
            setText(name+name+"下载失败"+"目录不存在");
        }
    }

    // 设置开机画面
    public void copyBootAnimation() {
        String baPath = "/sdcard/Download/ba.zip";
        if (isExists(baPath)) {
            String r = runCommandSu("cp "+baPath+" "+getBootAnimationPath()+"bootanimation.zip");
            if (r.equals("")) {
                r = runCommandSu("chmod 0755 "+getBootAnimationPath()+"bootanimation.zip");
                if (r.equals("")) {
                    r = runCommandSu("du -h "+getBootAnimationPath()+"bootanimation.zip");
                    setText(r.equals("")?"设置失败":"开机画面设置成功:"+r+"，重启后生效");
                    delFile(baPath);
                } else setText(r);
            } else setText(r);
        } else setText("请检查"+baPath+"文件是否存在");
    }

    // 清除开机画面
    public void clearAnimation() {
        String command = "rm -f "+getBootAnimationPath()+"bootanimation.zip";
        String r = runCommandSu(command);
        MyUtil.showLog("clearAnimation", r);
        if (r.equals("")) {
            setText("开机画面清除成功，重启后生效");
        } else setText(r);
    }

    public String runCommandSu(String command) {
        Process process = null;
        String result = "";
        DataOutputStream os = null;
        DataInputStream is = null;
        try {
            System.out.println("*********runCommandSu**********");
            System.out.println(command);
            process = Runtime.getRuntime().exec("su");
            os = new DataOutputStream(process.getOutputStream());
            is = new DataInputStream(process.getInputStream());
            os.writeBytes(command + "\n");
            os.flush();
            os.writeBytes("exit\n");
            os.flush();
            String line = null;
            while ((line = is.readLine()) != null) {
                result += line;
            }
            int exit = process.waitFor();
            System.out.println(process.exitValue());
            process.destroy();
            if (exit == 0) {
                System.out.println("子进程正常完成1111111111111");
            } else {
                System.out.println("子进程异常结束22222222222222："+exit);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            result = e.getMessage();
        } catch (IOException e) {
            e.printStackTrace();
            result = e.getMessage();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (process != null) {
                process.destroy();
            }
        }
        return result;
    }

    public void setText(String s) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tvMsg.setText(s);
            }
        });
    }

    public Boolean isExists(String path) {
        File file = new File(path);
        return file.exists();
    }

    public String delFile(String filePath$Name) {
        File file = new File(filePath$Name);
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                MyUtil.showLog("--Method--", "Copy_Delete.deleteSingleFile: 删除单个文件" + filePath$Name + "成功！");
                return "success";
            } else {
                return filePath$Name+"删除失败";
            }
        } else {
            return filePath$Name+"不存在";
        }
    }


}